package cn.qicaiwang.open.system.task;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.qicaiwang.open.quartz.entity.SystemJobLog;
import cn.qicaiwang.open.quartz.service.SysJobLogService;
import cn.qicaiwang.open.system.model.entity.SystemLoginLog;
import cn.qicaiwang.open.system.model.entity.SystemOperLog;
import cn.qicaiwang.open.system.service.ISystemLoginLogService;
import cn.qicaiwang.open.system.service.ISystemOperLogService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author GAOXI
 * @Date:2025/7/20
 * @Description:    登录日志 操作日志定时清空
 * @version：1.0
 **/
@Slf4j
@Component("clearLogTask")
public class ClearLogTask {

    @Autowired
    private ISystemLoginLogService loginLogService;

    @Autowired
    private ISystemOperLogService operLogService;

    @Autowired
    private SysJobLogService jobLogService;

    @Transactional(rollbackFor = Exception.class)
    public void run(){
        Date date = new Date();
        DateTime lastWeek = DateUtil.offsetWeek(date,-1);

        QueryWrapper<SystemLoginLog> w1 = new QueryWrapper<>();
        w1.between("login_time",new Date() ,lastWeek);
        loginLogService.remove(w1);
        QueryWrapper<SystemOperLog> w2 = new QueryWrapper<>();
        w2.between("oper_time",new Date() ,lastWeek);
        operLogService.remove(w2);
        QueryWrapper<SystemJobLog> w3 = new QueryWrapper<>();
        w3.between("create_time",new Date() ,lastWeek);
        boolean remove = jobLogService.remove(w3);
        if (remove) {
            log.info("日志清空定时执行成功 清空范围 {}——{}",lastWeek,DateUtil.formatDateTime(date));
        }else {
            log.error("日志清空定时执行失败 清空范围 {}——{}",lastWeek,DateUtil.formatDateTime(date));
        }
    }
}
